

import React, { useState, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import styles from './styles.module.css';
import Header from '../../components/Header';

interface HistoryItem {
  id: string;
  title: string;
  description: string;
  category: string;
  type: string;
  progress: number;
  lastStudyTime: string;
  duration: string;
  author: string;
  imageUrl: string;
  categoryColor: string;
  typeColor: string;
  progressColor: string;
  buttonText: string;
  buttonColor: string;
}

const UserHistoryPage: React.FC = () => {
  const navigate = useNavigate();
  const [historySearchValue, setHistorySearchValue] = useState('');
  const [categoryFilter, setCategoryFilter] = useState('');
  const [typeFilter, setTypeFilter] = useState('');
  const [sortFilter, setSortFilter] = useState('recent');
  const [currentPage, setCurrentPage] = useState(1);

  // 设置页面标题
  useEffect(() => {
    const originalTitle = document.title;
    document.title = '学习历史 - 精进坊';
    return () => { document.title = originalTitle; };
  }, []);

  // 模拟学习历史数据
  const [historyItems] = useState<HistoryItem[]>([
    {
      id: 'content1',
      title: '批判性思维：如何建立理性思考框架',
      description: '掌握批判性思维的核心方法，学会独立思考和理性判断，提升决策质量。',
      category: '认知提升',
      type: '视频',
      progress: 75,
      lastStudyTime: '2小时前',
      duration: '35分钟',
      author: '张教授',
      imageUrl: 'https://s.coze.cn/image/QE6Wl1yDnJ0/',
      categoryColor: 'bg-secondary',
      typeColor: 'bg-blue-100 text-blue-600',
      progressColor: styles.progressBar,
      buttonText: '继续学习',
      buttonColor: 'bg-secondary hover:bg-accent'
    },
    {
      id: 'content2',
      title: '30天全身训练计划：从零开始塑造完美身材',
      description: '科学的训练计划，适合初学者的全身锻炼方案，帮助你建立运动习惯。',
      category: '身体健身',
      type: '文章',
      progress: 100,
      lastStudyTime: '昨天',
      duration: '已完成',
      author: '健身教练李老师',
      imageUrl: 'https://s.coze.cn/image/UMp2PcUWwXE/',
      categoryColor: 'bg-green-500',
      typeColor: 'bg-green-100 text-green-600',
      progressColor: 'bg-green-500',
      buttonText: '重新学习',
      buttonColor: 'bg-green-500 hover:bg-green-600'
    },
    {
      id: 'content3',
      title: '费曼学习法：如何快速掌握新知识',
      description: '通过费曼技巧，学会用简单的语言解释复杂概念，加深理解和记忆。',
      category: '学习能力',
      type: '视频',
      progress: 45,
      lastStudyTime: '3天前',
      duration: '22分钟',
      author: '学习专家王老师',
      imageUrl: 'https://s.coze.cn/image/qpYiidw6VR0/',
      categoryColor: 'bg-purple-500',
      typeColor: 'bg-blue-100 text-blue-600',
      progressColor: 'bg-purple-500',
      buttonText: '继续学习',
      buttonColor: 'bg-purple-500 hover:bg-purple-600'
    },
    {
      id: 'content4',
      title: '如何运用第一性原理进行创新思考',
      description: '深度解析埃隆·马斯克的思维模式，学会从根本上解决问题的方法。',
      category: '认知提升',
      type: '文章',
      progress: 60,
      lastStudyTime: '1周前',
      duration: '15分钟',
      author: '思维专家陈老师',
      imageUrl: 'https://s.coze.cn/image/Nh6zo3M2gL8/',
      categoryColor: 'bg-secondary',
      typeColor: 'bg-green-100 text-green-600',
      progressColor: styles.progressBar,
      buttonText: '继续阅读',
      buttonColor: 'bg-secondary hover:bg-accent'
    },
    {
      id: 'content5',
      title: 'HIIT高强度间歇训练的科学原理',
      description: '了解HIIT训练的生理机制，制定高效的燃脂计划。',
      category: '身体健身',
      type: '视频',
      progress: 25,
      lastStudyTime: '2周前',
      duration: '8分钟',
      author: '运动专家刘老师',
      imageUrl: 'https://s.coze.cn/image/q4Es0QVcJvM/',
      categoryColor: 'bg-green-500',
      typeColor: 'bg-blue-100 text-blue-600',
      progressColor: 'bg-green-500',
      buttonText: '继续学习',
      buttonColor: 'bg-green-500 hover:bg-green-600'
    }
  ]);

  // 筛选逻辑
  const filteredItems = historyItems.filter(item => {
    const matchesSearch = item.title.toLowerCase().includes(historySearchValue.toLowerCase()) ||
                         item.description.toLowerCase().includes(historySearchValue.toLowerCase());
    
    const matchesCategory = !categoryFilter || 
      (categoryFilter === 'cognition' && item.category === '认知提升') ||
      (categoryFilter === 'fitness' && item.category === '身体健身') ||
      (categoryFilter === 'learning' && item.category === '学习能力');
    
    const matchesType = !typeFilter || 
      (typeFilter === 'article' && item.type === '文章') ||
      (typeFilter === 'video' && item.type === '视频');
    
    return matchesSearch && matchesCategory && matchesType;
  });

  // 继续学习按钮点击
  const handleContinueLearning = (e: React.MouseEvent, contentId: string) => {
    e.stopPropagation();
    navigate(`/content-detail?id=${contentId}&from=history`);
  };

  // 历史卡片点击
  const handleHistoryCardClick = (contentId: string) => {
    navigate(`/content-detail?id=${contentId}&from=history`);
  };

  // 分页处理
  const handlePageChange = (page: number) => {
    setCurrentPage(page);
  };

  return (
    <div className={styles.pageWrapper}>
      {/* 头部栏 */}
      <Header currentPage="" />

      {/* 主布局容器 */}
      <div className="pt-16 min-h-screen">
        {/* 主内容区 */}
        <main className="p-6">
          {/* 页面头部 */}
          <div className="mb-8">
            <div className="flex items-center justify-between">
              <div>
                <h2 className="text-2xl font-bold text-text-primary mb-2">学习历史</h2>
                <nav className="text-sm text-text-secondary">
                  <span>首页</span>
                  <i className="fas fa-chevron-right mx-2"></i>
                  <span>个人中心</span>
                  <i className="fas fa-chevron-right mx-2"></i>
                  <span className="text-secondary">学习历史</span>
                </nav>
              </div>
              <div className="flex items-center space-x-6">
                <div className="text-center">
                  <div className="text-2xl font-bold text-secondary">156</div>
                  <div className="text-xs text-text-secondary">总学习时长(小时)</div>
                </div>
                <div className="text-center">
                  <div className="text-2xl font-bold text-accent">48</div>
                  <div className="text-xs text-text-secondary">学习内容数</div>
                </div>
                <div className="text-center">
                  <div className="text-2xl font-bold text-green-500">7</div>
                  <div className="text-xs text-text-secondary">连续天数</div>
                </div>
              </div>
            </div>
          </div>

          {/* 工具栏区域 */}
          <div className={`${styles.contentCard} rounded-card shadow-card p-6 mb-6`}>
            <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between space-y-4 lg:space-y-0">
              {/* 搜索框 */}
              <div className="flex-1 lg:max-w-md">
                <div className="relative">
                  <input 
                    type="text" 
                    placeholder="搜索学习历史..." 
                    value={historySearchValue}
                    onChange={(e) => setHistorySearchValue(e.target.value)}
                    className="w-full pl-10 pr-4 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-secondary focus:border-transparent"
                  />
                  <i className="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                </div>
              </div>
              
              {/* 筛选和排序 */}
              <div className="flex flex-wrap items-center gap-3">
                {/* 分类筛选 */}
                <div className="relative">
                  <select 
                    value={categoryFilter}
                    onChange={(e) => setCategoryFilter(e.target.value)}
                    className="appearance-none bg-white border border-gray-200 rounded-lg px-4 py-2 pr-8 focus:outline-none focus:ring-2 focus:ring-secondary focus:border-transparent"
                  >
                    <option value="">全部分类</option>
                    <option value="cognition">认知提升</option>
                    <option value="fitness">身体健身</option>
                    <option value="learning">学习能力</option>
                  </select>
                  <i className="fas fa-chevron-down absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 pointer-events-none"></i>
                </div>
                
                {/* 内容类型筛选 */}
                <div className="relative">
                  <select 
                    value={typeFilter}
                    onChange={(e) => setTypeFilter(e.target.value)}
                    className="appearance-none bg-white border border-gray-200 rounded-lg px-4 py-2 pr-8 focus:outline-none focus:ring-2 focus:ring-secondary focus:border-transparent"
                  >
                    <option value="">全部类型</option>
                    <option value="article">文章</option>
                    <option value="video">视频</option>
                  </select>
                  <i className="fas fa-chevron-down absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 pointer-events-none"></i>
                </div>
                
                {/* 排序 */}
                <div className="relative">
                  <select 
                    value={sortFilter}
                    onChange={(e) => setSortFilter(e.target.value)}
                    className="appearance-none bg-white border border-gray-200 rounded-lg px-4 py-2 pr-8 focus:outline-none focus:ring-2 focus:ring-secondary focus:border-transparent"
                  >
                    <option value="recent">最近学习</option>
                    <option value="duration">学习时长</option>
                    <option value="progress">完成度</option>
                  </select>
                  <i className="fas fa-chevron-down absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 pointer-events-none"></i>
                </div>
              </div>
            </div>
          </div>

          {/* 学习历史内容展示区 */}
          <div className="space-y-4 mb-8">
            {filteredItems.map((item) => (
              <div 
                key={item.id}
                className={`${styles.contentCard} rounded-card shadow-card p-6 ${styles.cardHover} cursor-pointer`}
                onClick={() => handleHistoryCardClick(item.id)}
              >
                <div className="flex space-x-4">
                  <img 
                    src={item.imageUrl} 
                    alt={`${item.title}封面`} 
                    className="w-24 h-24 object-cover rounded-lg"
                  />
                  <div className="flex-1">
                    <div className="flex items-start justify-between mb-2">
                      <div className="flex-1">
                        <div className="flex items-center space-x-2 mb-1">
                          <span className={`${item.categoryColor} text-white px-2 py-1 rounded-full text-xs`}>
                            {item.category}
                          </span>
                          <span className={`${item.typeColor} px-2 py-1 rounded-full text-xs`}>
                            {item.type}
                          </span>
                        </div>
                        <h4 className="font-semibold text-text-primary mb-2 line-clamp-2">
                          {item.title}
                        </h4>
                        <p className="text-text-secondary text-sm mb-3 line-clamp-2">
                          {item.description}
                        </p>
                      </div>
                    </div>
                    
                    {/* 学习进度 */}
                    <div className="mb-3">
                      <div className="flex justify-between items-center mb-1">
                        <span className="text-sm text-text-secondary">
                          {item.type === '文章' ? '阅读进度' : '学习进度'}
                        </span>
                        <span className="text-sm font-medium text-text-primary">{item.progress}%</span>
                      </div>
                      <div className="w-full bg-gray-200 rounded-full h-2">
                        <div 
                          className={`${item.progressColor} h-2 rounded-full`} 
                          style={{ width: `${item.progress}%` }}
                        ></div>
                      </div>
                    </div>
                    
                    <div className="flex items-center justify-between">
                      <div className="flex items-center space-x-4 text-xs text-text-secondary">
                        <span>
                          <i className="fas fa-clock mr-1"></i>
                          上次学习：{item.lastStudyTime}
                        </span>
                        <span>
                          <i className={`fas ${item.type === '文章' ? 'fa-book' : 'fa-play'} mr-1`}></i>
                          {item.type === '文章' ? `已阅读：${item.duration}` : `已学习：${item.duration}`}
                        </span>
                        <span>
                          <i className="fas fa-user mr-1"></i>
                          {item.author}
                        </span>
                      </div>
                      <button 
                        className={`px-4 py-1 ${item.buttonColor} text-white rounded-lg text-sm transition-colors`}
                        onClick={(e) => handleContinueLearning(e, item.id)}
                      >
                        {item.buttonText}
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>

          {/* 分页区域 */}
          <div className={`${styles.contentCard} rounded-card shadow-card p-4`}>
            <div className="flex items-center justify-between">
              <div className="text-sm text-text-secondary">
                显示第 <span className="font-medium text-text-primary">1-5</span> 条，共 <span className="font-medium text-text-primary">23</span> 条记录
              </div>
              
              <div className="flex items-center space-x-2">
                <button 
                  className="px-3 py-1 border border-gray-200 rounded-lg text-sm text-text-secondary hover:bg-gray-50 disabled:opacity-50" 
                  disabled={currentPage === 1}
                  onClick={() => handlePageChange(currentPage - 1)}
                >
                  <i className="fas fa-chevron-left mr-1"></i>上一页
                </button>
                
                <div className="flex space-x-1">
                  {[1, 2, 3].map((page) => (
                    <button 
                      key={page}
                      className={`px-3 py-1 rounded-lg text-sm ${
                        currentPage === page ? styles.paginationActive : 'text-text-secondary hover:bg-gray-50'
                      }`}
                      onClick={() => handlePageChange(page)}
                    >
                      {page}
                    </button>
                  ))}
                  <span className="px-2 py-1 text-text-secondary">...</span>
                  <button 
                    className="px-3 py-1 rounded-lg text-sm text-text-secondary hover:bg-gray-50"
                    onClick={() => handlePageChange(5)}
                  >
                    5
                  </button>
                </div>
                
                <button 
                  className="px-3 py-1 border border-gray-200 rounded-lg text-sm text-text-secondary hover:bg-gray-50"
                  onClick={() => handlePageChange(currentPage + 1)}
                >
                  下一页<i className="fas fa-chevron-right ml-1"></i>
                </button>
              </div>
            </div>
          </div>
        </main>
      </div>
    </div>
  );
};

export default UserHistoryPage;

